/**
 * 编辑菜单项和菜单项的按钮的窗体
 * @author Linzongxue 2012-1-6
 */
define(function(){
	//按钮记录的类型，用于在按钮表格中显示和添加行
	var ButtonRecord =  Ext.data.Record.create(['id', 'text', 'name', 'iconCls', 'value', 'tooltip']);
	//主窗口
	var MenuWindow = Ext.extend(Ext.Window, {
		resizable: false,
		modal: true,
	    animateTarget: cu.getDefaultAnimateTarget(),
        bodyStyle:'padding:3px;',
		iconCls: 'icon-window',
		buttonAlign: 'left',
		initComponent: function(){
			this.title = this.modifiedId ? '修改菜单项' : '添加菜单项';
			this.width = cu.getWinWidth(600);
			this.items = [
			    this.formPanel = this.createFormPanel(),
			    this.buttonGrid = this.createButtonGrid()
			];
			this.buttons = this.createButtons();
			MenuWindow.superclass.initComponent.call(this);
			this.initFormData();
			this.on('show', function(){
				this.firstFocus();
				cu.bindEnter(this, this.save);
			});
		},
		modifiedId: null, //从构造器中传入，表示要编辑的对象的id，为空表示新增
		parentMenu: null, //在构造器中传入，表示要编辑对象的父节点
		/**
		 * 保存菜单项和按钮，菜单项的数据在表单中，但按钮的数据在列表中，需要提取出来放到请求参数里
		 */
		save: function(continueToAdd){
			//组合按钮参数，应spring mvc的要求，对象数组或列表参数需要添加下标
			var buttonData = {};
			var store = this.buttonGrid.getStore();
			for (var row = 0; row < store.getCount(); row ++){
				var record = store.getAt(row);
				if (!record.get('text') || !record.get('name')){
					cu.alert('第' + (row + 1) + '个按钮的标题或名称为空，请填写');
					return;
				}
				store.fields.eachKey(function(fieldName){
					buttonData['buttons[' + row + '].' + fieldName] = record.get(fieldName);
				});
			}
			//提交表单
			cu.submit({
				form: this.getForm(), 
				url: 'sys/menu/saveMenuItem.do',
				params: buttonData,
				success: function(data){
					if (this.callback){
						var parentNode = this.getField('menuItem.parentId').getValueNode();
						this.callback.call(this.cbScope, parentNode.getPath(), data);
					}
					continueToAdd ? this.resetForm() : this.close();
				}, 
				scope:this
			});
		},
		initFormData: function(){
			if (!this.modifiedId) return;
			cu.get({
				url:'sys/menu/getMenuItem.do', 
				params: {menuId: this.modifiedId},
				success: function(data){
					//设置菜单项数据
					this.getForm().setValues(lu.addPrefToProps(data.menuItem, 'menuItem.'));
					//设置按钮数据
					Ext.each(data.buttons, function(btn){
						this.buttonGrid.addButton(btn);
					}, this);
				}, 
				scope: this
			});
		},
		createButtons: function(){
			var buttons = [];
			buttons.push({text: '测试', width:60, handler:this.testMenu, iconCls: 'icon-ok', scope: this, tooltip:'测试菜单是否正常显示'});
			buttons.push('->');
			if (!this.modifiedId){
				buttons.push({text: '保存并新增', width:90, handler: function(){this.save(true);}, iconCls: 'icon-save', scope: this});
			}
			buttons.push({text: '保存', width:60, handler: function(){this.save(false);}, iconCls: 'icon-save', scope: this});
			buttons.push({text: '关闭', width:60, handler: this.close, iconCls: 'icon-close', scope: this});
			return buttons;
		},
		createFormPanel: function(){
			var menuWin = this;
			var formPanel = new Ext.form.FormPanel({
			    baseCls: 'x-plain',
			    bodyStyle:'padding:5px;',
			    labelPad: 5,
			    labelWidth: 80,
			    labelAlign: "right",
			    items: [
			        {xtype:'hidden',name:'menuItem.id'},
			        {
			        	baseCls: 'x-plain',
			        	layout : 'column',
						border : false,
						defaults: {columnWidth : .5, layout : 'form', border : false},
						items : [{
							baseCls: 'x-plain',
							layout : 'form',
						    defaults: {anchor:'99%'},
							items:[{
								xtype:'combotree',
								fieldLabel:'* 所属目录',
								hiddenName: 'menuItem.parentId',
								value: this.modifiedId ? null : this.parentMenu.id,
								height: 200,
								dataUrl: 'sys/menu/getMenuFolders.do',
								nodePathUrl: 'sys/util/getEntityAttrPath.do?c=sys.Menu',
								root: {id:'root', text:'根目录', expanded: true},
								rootVisible: true,
								rootSelectable: true,
								rootValue: null,
								showFullPath: true,
								allowBlank: false,
						        validator: function(value){
						        	var selfId = menuWin.getField('menuItem.id').getValue();
						        	var parentId = menuWin.getField('menuItem.parentId').getValue();
						        	return parentId != selfId ? true : "父菜单不能是自身";
						        }
							},{
								xtype:'textfield',
					        	name: 'menuItem.name',
					        	fieldLabel: '名称',
					        	listeners:{
					        		render: function(){
					        			cu.tips(this, '程序内部使用的名称，命名格式为xx.xx.xx');
					        		}
					        	}
							}]
						},{
							baseCls: 'x-plain',
						    defaults: {anchor:'99%'},
							items:[{
					        	xtype:'textfield',
					        	name: 'menuItem.text',
					        	fieldLabel: '* 标题',
					        	maxLength: 30, 
					        	maxLengthText: '标题不能超过30个字',
					        	allowBlank:false,
					        	listeners:{
					        		render: function(){
					        			cu.tips(this, '用于显示的本文');
					        		}
					        	}
							},{
								xtype:'textfield',
					        	name: 'menuItem.iconCls',
					        	fieldLabel: '图标'
							}]
						}]
			        },{
			        	xtype:'textfield',
			        	name: 'menuItem.value',
			        	fieldLabel: '* 目标值',
			        	allowBlank: false,
			        	anchor:'99%',
			        	listeners:{
			        		render: function(){
			        			cu.tips(this, '<nobr>此字段填写js模块名或一段js代码(js代码必须以“js:”开头)。</nobr></br><b>双击输入框可直接选择js模块</b>');
			        			this.el.on('dblclick', function(){
			        				menuWin.toSelectJsModule(this);
			        			});
			        		}
			        	}
			        },{
			        	baseCls: 'x-plain',
			        	layout : 'column',
						border : false,
						defaults: {columnWidth : .5, layout : 'form', border : false},
						items:[{
							baseCls: 'x-plain',
						    defaults: {anchor:'99%'},
							items:[{
								xtype:'textfield',
					        	name: 'menuItem.tooltip',
					        	fieldLabel: '提示信息'
							}]
						},{
							baseCls: 'x-plain',
						    defaults: {anchor:'99%'},
							items:[{
								xtype: 'numberfield',
								name: 'menuItem.sortNum',
								fieldLabel: '排序号',
								value: 1
							}]
						}]
					}
			    ]
			});
			return formPanel;
		},
		createButtonGrid: function(){
			//按钮记录的类型，用于在按钮表格中显示和添加行
			var ButtonRecord =  Ext.data.Record.create(['id', 'text', 'name']);
			var store = new Ext.data.JsonStore({recordType: ButtonRecord});
			var addButton = function(cfg){
				store.add(new ButtonRecord(cfg));
                grid.startEditing(store.getCount() - 1, 0);
			};
			var addCommonButtons = function(){
				addButton({text:'添加', name:'add'});
				addButton({text:'修改', name:'modify'});
				addButton({text:'删除', name:'remove'});
			};
			var moveRow = function(dir){
				var up = (dir === 'up');
				var record = grid.getSelectionModel().getSelected();
				if (!record) return;
				var index = store.indexOf(record); //找到行号
				var newIndex = (up ? index - 1 : index + 1); //计算新行号
				if (newIndex < 0 || newIndex > store.getCount() - 1) return;
				store.removeAt(index); //删除旧行
				store.insert(newIndex, record); //插入新行
				grid.getSelectionModel().selectRow(newIndex); //重新选中新行
			};
			var grid = new Ext.grid.EditorGridPanel({
				height: 180,
				stripeRows: true,
			    enableHdMenu: false,
			    clicksToEdit: 1,
			    autoExpandColumn: 1,
			    sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
				tbar: [
				    {xtype: 'label', text: '授权按钮列表', style:'font-weight:bold;'}, '->',
				    {text:'添加', handler: function(){addButton();}, iconCls:'icon-add', tooltip:'添加一个按钮'},
				    {text: '增删改', handler: addCommonButtons, iconCls:'icon-add', tooltip:'添加常用的“添加”、“修改”和“删除”按钮'},
				    '-',
				    {handler: function(){moveRow('up');}, iconCls:'icon-up', tooltip:'行上移'},
				    {handler: function(){moveRow('down');}, iconCls:'icon-down', tooltip:'行下移'}
				],
				store: store,
				columns:[
				    {header: '名称', width: 180, dataIndex: 'name', editor: {allowBlank: false}},
					{header: '标题', width: 150, dataIndex: 'text', editor: {allowBlank: false}},
					{
						xtype: 'actioncolumn',width: 30, items: [{
		                    icon: cu.getIconImg('cancel.gif'),
		                    tooltip: '<nobr>删除此行</nobr>',
		                    handler: function(grid, rowIndex, colIndex) {
		                        grid.getStore().removeAt(rowIndex);
		                    }
		                }]
					}
				],
				bbar:[{
					xtype:'label', text:'说明：授权按钮是指要做权限控制的按钮，它可以只是一个抽象，' + 
						'并通过“名称”属性来标识某个用户是否具有此权限。'
				}]
			});
			grid.addButton = addButton;
			return grid;
		},
		//打开窗口选择js模块
		toSelectJsModule: function(el){
			use('sys.menu.SelectJsModuleWindow', function(Win){
				new Win({
					callback: function(data){
						el.dom.value = data;
						el.focus();
						this.getForm().clearInvalid();
					},
					cbScope: this
				}).show();
			}, this);
		},
		//测试菜单是否正常
		testMenu: function(){
			if (!this.getForm().isValid()){
				cu.hint('表单验证不通过'); return;
			}
			var target = this.getField('menuItem.value').getValue();
			if (target.match(/^js\s*:/)){
				var js = target.replace(/^js\s*:/, '').trim();
				(new Function(js))();
			}
			else{
				use(target, function(Panel){
					new Ext.Window({
						layout: 'fit',
						modal: true,
						title: '::菜单测试:: - ' + this.getField('menuItem.text').getValue(),
						width:  cu.getWinWidth(800), height: cu.getWinHeight(600),
						iconCls: 'icon-window',
						items: new Panel(),
						buttons:[{
							text: '关闭', iconCls: 'icon-close', handler: function(btn){btn.ownerCt.ownerCt.close();}
						}]
					}).show();
				}, this);
			}
		},
		resetForm: function(){
			this.getField('menuItem.text').setValue(null);
			this.getField('menuItem.name').setValue(null);
			this.getField('menuItem.value').setValue(null);
			this.getField('menuItem.iconCls').setValue(null);
			this.getField('menuItem.tooltip').setValue(null);
			this.getForm().clearInvalid();
			this.buttonGrid.getStore().removeAll();
		},
		getForm: function(){
			return this.formPanel.getForm();
		},
		getField: function(name){
			return this.getForm().findField(name);
		},
	    firstFocus: function(){
	    	this.getField('menuItem.text').focus(false,500);
	    }
	});
	return MenuWindow;
});